/**
 * Created by Julia on 2016/05/04.
 */
define(['jquery', 'domReady!', 'appLocalStorage', 'appConst', 'model/global', 'appMessageBox', 'jeditable/jquery.jeditable'], function ($, domReady, appLocalStorage, appConst, global, msgBox) {
    var search_project_key = appConst.searchKey.search_dataImport_project_key + global.getUserId();
    var that;
    return {
        init: function () {
            that = this;
        },
        runDataTables: function () {
            var projectId = null;
            var customParams = function (params) {
                var queryParameter = appLocalStorage.getLocal(search_project_key);
                if (queryParameter != null) {
                    queryParameter = JSON.parse(queryParameter);
                    projectId = queryParameter.search_projectId;
                }
                params['search_projectId'] = projectId;
                params['draw'] = params.draw;
                return params;
            };
            var dt_colTable = $('#dt_cpw').dataTable({

                /*"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'><'col-sm-6 col-xs-12 hidden-xs'>r>" +
                 "t" +
                 "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",*/
                "sDom": "<'row'<'col-sm-12' t>> <'row'<'col-sm-5' i><'col-sm-7' p>>",
                "paging": false,
                "searching": false,
                "autoWidth": false,
                "language": appConst.table_language(),
                "ordering": false,
                "serverSide": true,
                "ajax": {
                    "url": "psAttribute/findPSAttribute",
                    "type": "POST",
                    "dataSrc": "body",
                    "traditional": true,
                    "data": customParams,
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                },
                "columns": [
                    {"data": null},
                    {"data": "name"},
                    {"data": "value"},
                    {"data": "isDefault"},
                    {"data": "isDefault"},
                    {"data": "isShow"}
                ],
                "columnDefs": [
                    {
                        "targets": [2],
                        "createdCell": function (td, cellData, rowData, row, col) {
                            $(td).addClass('inputTd').attr('data-code', 'td_value' + '_' + rowData.id + '_' + rowData.isDefault + "_" + rowData.project.id);
                        }

                    },
                    {
                        "targets": [3],
                        "visible": false,
                        "render": function (data, type, full) {
                            var result = "";
                            if (data == true) {
                                result = "YES";
                            } else if (data == false) {
                                result = "NO";
                            }
                            return result;
                        }

                    },
                    {
                        "targets": [4],
                        "render": function (data, type, full) {
                            var id = full.id;
                            var operate = "";
                            if (data == true) {
                                operate = "<div class='center'></div>"
                            } else if (data == false) {
                                operate = "<div class='center'><a href='javascript:void(0);' id='" + id + "' class='deletePSAConfirm_DI'>Delete</a></div>";
                            }
                            return operate;
                        }
                    },
                    {
                        "targets": [5],
                        "render": function (data, type, full) {
                            var id = full.id;
                            var operate = "";
                            var code = full.id + '_' + full.isDefault;
                            var v = full.value;
                            if (data == true) {
                                operate = "<input type='checkbox' name='checkbox' id='" + v + "'value=" + code + " checked='checked'/>";
                            } else if (data == false) {
                                operate = "<input type='checkbox' id='" + v + "' value=" + code + " name='checkbox'/>";
                            }
                            return operate;
                        }
                    }
                ],
                "drawCallback": function (settings) {
                    var api = this.api();
                    $('#dt_cpw tbody td.inputTd').jeditable(function (value, settings) {
                        var cell = api.cell(this);
                        cell.data(value);
                        var code = $(this).attr('data-code');
                        var arr = code.split('_');
                        var id = arr[2];
                        var name = arr[1];
                        var isDefault = arr[3];
                        var projectId = arr[4];
                        var value = cell.data().trim();
                        if (value == "") {
                            $(this).attr("style", "background: #fff0f0;font-size:12px;color: #D56161");
                            return false;
                        }
                        var obj = {
                            id: id,
                            "project": {id: projectId},
                            isDefault: isDefault
                        };
                        if (name == 'value') {
                            obj.value = value;
                        }

                        var array = new Array();
                        array.push(obj);
                        global.ajaxHasParams("psAttribute/updatePSA", array, function (data) {
                            that.saveTipInfo(data);
                        });
                    }, {
                        height: '20',
                        width: '200',
                        //onblur:'ignore',
                        cssclass: 'smart-form',
                        placeholder: $.i18n.prop("VALIDATE_ATTRIBUTE")
                    });

                }
            });
            $('#dt_cpw tbody').on('click', 'tr input[name="checkbox"]', function () {
                var code = $(this).attr('value');
                var arr = code.split('_');
                var id = arr[0];
                var value = $(this).attr('id');
                var isDefault = arr[1];
                if ($(this).is(':checked')) {
                    var show = true;
                } else {
                    var show = false;
                }
                var obj = {
                    id: id,
                    value: value,
                    isDefault: isDefault,
                    isShow: show,
                    "project": {id: projectId}
                };
                var array = new Array();
                array.push(obj);
                global.ajaxHasParams("psAttribute/updatePSA", array, function (data) {
                    that.saveTipInfo(data);
                });
            });

            $("#attributeSubmit").click(function () {
                that.addPSA(projectId);
            });

            $('#dt_cpw').DataTable().on('draw.dt', function () {
                var dt = $(this).dataTable();
                dt.api().column(0, {draw: 'applied'}).nodes().each(function (cell, i) {
                    cell.innerHTML = i + 1;
                });
                $("#dt_cpw").find(".deletePSAConfirm_DI").unbind('click').on('click', function (obj) {
                    that.deletePSAConfirm($(this).attr("id"));
                });
            });
        },
        deletePSAConfirm: function (id) {
            msgBox.show({
                content: "" + $.i18n.prop("PSA_DELETE_SUBMIT") + " <p class='text-align-right'>" +
                "<button type='submit' id='" + id + "'  class='btn btn-primary btn-sm deletePSA_DI" + id + "'>" + $.i18n.prop("GLOBAL_BUTTON_YES") + "</button> " +
                "<a href='javascript:void(0);' class='btn btn-danger btn-sm'>" + $.i18n.prop("GLOBAL_BUTTON_NO") + "</a></p>",
                type: 'normal'
            });
            $("#divSmallBoxes").find(".deletePSA_DI" + id).unbind('click').on('click', function (data) {
                that.deletePSA($(this).attr("id"), data);
            });
        },
        deletePSA: function (id, data) {
            var errorTip = data.message != null ? $.i18n.prop(data.message, [$.i18n.prop('PROJECT_COLUMN')]) : $.i18n.prop('GLOBAL_DELETE_FAIL', [$.i18n.prop('PROJECT_COLUMN')]);
            global.ajaxNoParams("psAttribute/deleteDataImportPSA/" + id, function () {
                msgBox.show({
                    content: "" + $.i18n.prop('GLOBAL_DELETE_SUCCESS', [$.i18n.prop('PROJECT_COLUMN')]),
                    type: 'success'
                });
                $('#dt_cpw').DataTable().draw();
            }, function (e) {
                msgBox.show({
                    content: "" + errorTip,
                    type: 'error'
                });
            });
        },
        addPSA: function (id) {
            if (id == null || id == "") {
                $("#attributeId").parent().removeClass("state-success");
                $("#attributeId").parent().addClass("state-error");
                document.getElementById("add-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("VALIDATE_ATTRIBUTE_PROJECT") + "</font>";
                return;
            } else {
                $("#attributeId").parent().removeClass("state-error");
                $("#attributeId").parent().addClass("state-success");
                document.getElementById("add-label").innerHTML = "<font><em></em></font>";
            }


            var attributeValue = $("#attributeId").val();
            var column = document.getElementById('dt_cpw');
            var line = column.rows.length;  //获取当前行数
            var a;
            for (var j = 1; j < line; j++) {

                var cells0 = column.rows[j].cells[1].innerHTML;
                var cells1 = column.rows[j].cells[2].innerHTML;
                if ($.trim(attributeValue) == $.trim(cells1)) {
                    a = false;
                    break;
                }
                else {
                    if ($.trim(attributeValue) == $.trim(cells0)) {
                        a = false;
                        break;
                    } else
                        a = true;
                }
            }
            if ($.trim(attributeValue) != "") {
                $("#attributeId").parent().removeClass("state-error");
                $("#attributeId").parent().addClass("state-success");
                document.getElementById("add-label").innerHTML = "<font><em></em></font>";
            } else {
                $("#attributeId").parent().removeClass("state-success");
                $("#attributeId").parent().addClass("state-error");
                document.getElementById("add-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop("DATAIMPORT_ATTRIBUTE_NAME") + "</font>";
                return;
            }

            if (a == true) {
                $("#attributeId").parent().removeClass("state-error");
                $("#attributeId").parent().addClass("state-success");
                document.getElementById("add-label").innerHTML = "<font><em></em></font>";
                var obj = {
                    name: $.trim(attributeValue),
                    value: $.trim(attributeValue),
                    isDefault: false,
                    isShow: true
                };
                var array = new Array();
                array.push(obj);
                global.ajaxHasParams("psAttribute/addDataImportPSA/" + id, array, function (data) {
                    that.saveTipInfo(data);
                });
            } else {
                $("#attributeId").parent().removeClass("state-success");
                $("#attributeId").parent().addClass("state-error");
                document.getElementById("add-label").innerHTML = "<font color='color: #D56161'>" + $.i18n.prop('EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS', $.i18n.prop('PROJECT_COLUMN')) + "</font>";
            }
        },
        saveTipInfo: function (data) {
            var errorTip = data.message != null ? $.i18n.prop(data.message, [$.i18n.prop('PROJECT_COLUMN')]) : $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS", $.i18n.prop('PROJECT_COLUMN'));
            msgBox.show({
                title: data.code == 0 ? $.i18n.prop('MESSAGEBOX_TITLE_FAIL') : $.i18n.prop("MESSAGEBOX_TITLE_SUCCESS"),
                content: data.code == 0 ? errorTip : $.i18n.prop('PROJECT_SAVE_SUCCESS'),
                type: data.code == 0 ? 'error' : 'success'
            });
            $('#dt_cpw').DataTable().draw();
        }
    }
});

